# -*- coding: UTF-8 -*-
# Copyright 2020 YangZhongxi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and

from PyQt5.QtCore import QObject


class FileWriter(QObject):

    def __init__(self, filename):
        super().__init__()
        self.filename = filename
        self.file = None

    def open(self):
        if self.file is None:
            try:
                self.file = open(self.filename, "a")
                return True
            except OSError as err:
                print("打开文件[%s]失败: %s" % (self.filename, err))
        return False

    def close(self):
        if self.file is not None:
            self.file.close()
            self.file = None

    def write(self, message):
        if self.file is not None:
            self.file.write(message)
            self.file.flush()
